from flask import Flask, request, jsonify, make_response
from extensions import db, cors
from sqlalchemy import null, text
from flask_marshmallow import Marshmallow
from flask_restful import Api, Resource

import json
import datetime
import requests

import config
from models import User,SearchHistory,SeedKey,SeedKeyFrequency,MidKey,Compkey,CompKeyFrequency,CompkeyFinal
import compkey



url_prefix = "http://127.0.0.1:5000/"
headers = {
  'Content-Type': 'application/json'
}



app = Flask(__name__)
# 绑定配置文件
app.config.from_object(config)
# 初始化数据库
db.init_app(app)
# 跨域请求
cors.init_app(app)
# 数据格式转换
ma = Marshmallow(app)
# restful API 接口格式
api = Api(app, default_mediatype="application/json")

@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'

# -----------------------------------数据库表schema-----------------------------------
class UserSchema(ma.Schema):
    class Meta:
        fields = ("id", "username", "password")
user_schema = UserSchema()
users_schema = UserSchema(many=True)

class SeedKeySchema(ma.Schema):
    class Meta:
        fields = ("id", "seedkeyname", "volume", "logdate", "loglength")
seedkey_schema = SeedKeySchema()
seedkeys_schema = SeedKeySchema(many=True)

class SearchHistorySchema(ma.Schema):
    class Meta:
        fields = ("id", "userid", "seedkeyid", "searchtime")
searchhistory_schema = SearchHistorySchema()
searchhistorys_schema = SearchHistorySchema(many=True)

class SeedKeyFrequencySchema(ma.Schema):
    class Meta:
        fields = ("id", "seedkeyid", "date", "frequency")
seedkeyfrequency_schema = SeedKeyFrequencySchema()
seedkeyfrequencys_schema = SeedKeyFrequencySchema(many=True)

class MidKeySchema(ma.Schema):
    class Meta:
        fields = ("id", "seedkeyid", "midkeyname", "midkeyvalue")
midkey_schema = MidKeySchema()
midkeys_schema = MidKeySchema(many=True)

class CompkeySchema(ma.Schema):
    class Meta:
        fields = ("id", "seedkeyid", "midkeyid", "compkeyname", "compkeyvalue")
compkey_schema = CompkeySchema()
compkeys_schema = CompkeySchema(many=True)

class CompKeyFrequencySchema(ma.Schema):
    class Meta:
        fields = ("id", "compkeyid", "date", "frequency")
compkeyfrequency_schema = CompKeyFrequencySchema()
compkeyfrequencys_schema = CompKeyFrequencySchema(many=True)

class CompkeyFinalSchema(ma.Schema):
    class Meta:
        fields = ("id", "seedkeyid", "compkeyname", "value")
compkeyfinal_schema = CompkeyFinalSchema()
compkeyfinals_schema = CompkeyFinalSchema(many=True)


# --------------------------------------api接口--------------------------------------
# 用户模块 /users
class Users(Resource):

    # 获取所有用户信息
    def get(self):  # get请求
        user_all = User.query.all()
        return users_schema.dump(user_all)
    
    # 新增用户信息
    def post(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        add_username = q_dict["username"]
        add_password = q_dict["password"]

        add_user = User(
            username=add_username,
            password=add_password
        )
        try:
            db.session.add(add_user)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "用户添加失败，数据存在空值或不合法"}
        return {"code": 200,
                "msg": "成功添加用户"}

    # 更新用户信息
    def put(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析
        update_userid = q_dict["id"]
        update_username = q_dict["username"]
        update_password = q_dict["password"]
        update_user = User.query.filter(User.id == update_userid).first()
        try:
            update_user.username = update_username
            update_user.password = update_password
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "用户信息更新失败，用户不存在或数据不合法"}
        return {"code": 200,
                "msg": "成功更新用户信息"}

api.add_resource(Users, '/users')

# 用户模块 /users/<int:userid>
class UsersId(Resource):

    # 根据id获取用户信息
    def get(self, userid):
        user = User.query.filter(User.id == userid).first()  # 数据库查询第一个匹配的数据
        return user_schema.dump(user)

    # 删除用户信息
    def delete(self,userid):
        delete_user = User.query.filter(User.id == userid).first()
        try:
            db.session.delete(delete_user)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '用户删除失败，不存在该用户'}
        return {"code": 200,
                'msg': '用户删除成功'}

api.add_resource(UsersId, '/users/<int:userid>')

# 用户搜索历史 /history/<int:userid>
class Histories(Resource):
    # 获取所有用户搜索历史信息
    def get(self,userid):
        history_all = SearchHistory.query.all()
        return searchhistorys_schema.dump(history_all)

    def post(self,userid):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        add_seedkeyid = q_dict["seedkeyid"]
        add_searchtime = datetime.datetime.now().strftime('%Y-%m-%d')

        add_history = SearchHistory(
            userid=userid,
            seedkeyid=add_seedkeyid,
            searchtime = add_searchtime
        )
        try:
            db.session.add(add_history)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "搜索记录添加失败，数据存在空值或不合法"}
        return {"code": 200,
                "msg": "成功添加搜索记录"}

api.add_resource(Histories, '/history/<int:userid>')

# 用户搜索历史 /history/<int:historyid>
class HistoriesId(Resource):
    def delete(self,historyid):
        delete_history = SearchHistory.query.filter(SearchHistory.id == historyid).first()
        try:
            db.session.delete(delete_history)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '搜索记录删除失败，不存在该记录'}
        return {"code": 200,
                'msg': '搜索记录删除成功'}

api.add_resource(HistoriesId, '/history/<int:historyid>')

# 种子关键词模块 /seedkeys
class SeedKeys(Resource):

    # 获取所有查询过的种子关键词
    def get(self):
        seedkey_all = SeedKey.query.all()
        return seedkeys_schema.dump(seedkey_all)
    
    # 新增种子关键词
    def post(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        add_seedkeyname = q_dict["seedkeyname"]
        add_volume = q_dict["volume"]
        add_logdate = q_dict["logdate"]
        add_loglength = q_dict["loglength"]

        add_seedkey = SeedKey(
            seedkeyname = add_seedkeyname,
            volume = add_volume,
            logdate = add_logdate,
            loglength = add_loglength
        )
        try:
            db.session.add(add_seedkey)
            db.session.flush()
            add_id = add_seedkey.id
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "种子关键词添加失败，数据存在空值或不合法"}
        return {"id":add_id,
                "code": 200,
                "msg": "成功添加种子关键词"}

    # 更新种子关键词信息
    def put(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析
        update_seedkeyid = q_dict["id"]
        update_seedkeyname = q_dict["seedkeyname"]
        update_logdate = q_dict["logdate"]
        update_loglength = q_dict["loglength"]
        update_seedkey = SeedKey.query.filter(SeedKey.id == update_seedkeyid).first()
        try:
            update_seedkey.seedkeyname = update_seedkeyname
            update_seedkey.logdate = update_logdate
            update_seedkey.loglength = update_loglength
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "种子关键词信息更新失败，种子关键词不存在或数据不合法"}
        return {"code": 200,
                "msg": "成功更新种子关键词信息"}

api.add_resource(SeedKeys, '/seedkeys')

# 种子关键词模块 /seedkeys/<int:seedkeyid>
class SeedKeysId(Resource):
    # 根据id获取种子关键词信息
    def get(self, seedkeyid):
        seedkey = SeedKey.query.filter(SeedKey.id == seedkeyid).first()  # 数据库查询第一个匹配的数据
        return seedkey_schema.dump(seedkey)

    # 删除用户信息
    def delete(self,seedkeyid):
        delete_seedkey = SeedKey.query.filter(SeedKey.id == seedkeyid).first()
        try:
            db.session.delete(delete_seedkey)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '种子关键词删除失败，不存在该种子关键词'}
        return {"code": 200,
                'msg': '种子关键词删除成功'}

api.add_resource(SeedKeysId, '/seedkeys/<int:seedkeyid>')

# 种子关键词频率 /seedkeys/<int:seedkeyid>/frequency
class SeedKeysFrequency(Resource):

    # 获取种子关键词所有月份的词频信息
    def get(self, seedkeyid):
        seedkeyfrequencys = SeedKeyFrequency.query.filter(SeedKeyFrequency.seedkeyid == seedkeyid)  # 数据库查询所有匹配的数据
        return seedkeyfrequencys_schema.dump(seedkeyfrequencys)

api.add_resource(SeedKeysFrequency, '/seedkeys/<int:seedkeyid>/frequency')

# 中介关键词模块 /midkeys
class MidKeys(Resource):

    # 获取所有中介关键词
    def get(self):
        midkey_all = MidKey.query.all()
        return midkeys_schema.dump(midkey_all)
    
    # 新增中介关键词
    def post(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        add_seedkeyid = q_dict["seedkeyid"]
        add_midkeyname = q_dict["midkeyname"]
        add_midkeyvalue = q_dict["midkeyvalue"]

        add_midkey = MidKey(
            seedkeyid = add_seedkeyid,
            midkeyname = add_midkeyname,
            midkeyvalue = add_midkeyvalue
        )
        try:
            db.session.add(add_midkey)
            db.session.flush()
            add_id = add_midkey.id
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "中介关键词添加失败，数据存在空值或不合法"}
        return {"id": add_id,
                "code": 200,
                "msg": "成功添加中介关键词"}

    # 更新中介关键词信息
    def put(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        update_midkeyid = q_dict["id"]
        update_seedkeyid = q_dict["seedkeyid"]
        update_midkeyname = q_dict["midkeyname"]

        update_midkey = MidKey.query.filter(MidKey.id == update_midkeyid).first()
        try:
            update_midkey.seedkeyid = update_seedkeyid
            update_midkey.midkeyname = update_midkeyname
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "中介关键词信息更新失败，中介关键词不存在或数据不合法"}
        return {"code": 200,
                "msg": "成功更新中介关键词信息"}

api.add_resource(MidKeys, '/midkeys')

# 中介关键词模块 /midkeys/<int:seedkeyid>
class MidKeysSeedId(Resource):
    # 根据种子关键词id获取中介关键词信息
    def get(self, seedkeyid):
        midkeys = MidKey.query.filter(MidKey.seedkeyid == seedkeyid)  # 数据库查询所有匹配的数据
        return midkeys_schema.dump(midkeys)

    # 删除中介关键词信息
    def delete(self,seedkeyid):
        delete_midkeys = MidKey.query.filter(MidKey.seedkeyid == seedkeyid)
        try:
            db.session.delete(delete_midkeys)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '中介关键词删除失败，该种子关键词不存在中介关键词'}
        return {"code": 200,
                'msg': '该种子关键词的中介关键词删除成功'}

api.add_resource(MidKeysSeedId, '/midkeys/<int:seedkeyid>')

# 中介关键词模块 /midkeys/<int:midkeyid>
class MidKyesId(Resource):

    # 根据id获取中介关键词信息
    def get(self, midkeyid):
        midkey = MidKey.query.filter(MidKey.id == midkeyid).first()  # 数据库查询第一个匹配的数据
        return midkey_schema.dump(midkey)

    # 删除中介关键词信息
    def delete(self,midkeyid):
        delete_midkey = MiddKey.query.filter(MidKey.id == midkeyid).first()
        try:
            db.session.delete(delete_midkey)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '中介关键词删除失败，不存在该中介关键词'}
        return {"code": 200,
                'msg': '中介关键词删除成功'}

api.add_resource(MidKyesId, '/midkeys/<int:midkeyid>')

# 竞争性关键词模块 /compkeys
class CompKeys(Resource):

    # 获取所有竞争性关键词
    def get(self):
        compkey_all = Compkey.query.all()
        return compkeys_schema.dump(compkey_all)
    
    # 新增竞争性关键词
    def post(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        add_seedkeyid = q_dict["seedkeyid"]
        add_midkeyid = q_dict["midkeyid"]
        add_compkeyname = q_dict["compkeyname"]
        add_compkeyvalue = q_dict["compkeyvalue"]

        add_compkey = Compkey(
            seedkeyid = add_seedkeyid,
            midkeyid = add_midkeyid,
            compkeyname = add_compkeyname,
            compkeyvalue = add_compkeyvalue
        )
        try:
            db.session.add(add_compkey)
            db.session.flush()
            add_id = add_compkey.id
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "竞争性关键词添加失败，数据存在空值或不合法"}
        return {"id": add_id,
                "code": 200,
                "msg": "成功添加竞争性关键词"}

    # 更新竞争性关键词信息
    def put(self):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        update_compkeyid = q_dict["id"]
        update_seedkeyid = q_dict["seedkeyid"]
        update_midkeyid = q_dict["midkeyid"]
        update_compkeyname = q_dict["compkeyname"]
        update_compkeyvalue = q_dict["compkeyvalue"]

        update_compkey = CompKey.query.filter(CompKey.id == update_compkeyid).first()
        try:
            update_compkey.seedkeyid = update_seedkeyid
            update_compkey.midkeyid = update_midkeyid
            update_compkey.compkeyname = update_compkeyname
            update_compkey.compkeyvalue = update_compkeyvalue
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "竞争性关键词信息更新失败，竞争性关键词不存在或数据不合法"}
        return {"code": 200,
                "msg": "成功更新竞争性关键词信息"}

api.add_resource(CompKeys, '/compkeys')

# 竞争性关键词模块 /compkeys/<int:midkeyid>
class CompKeysMidKeyId(Resource):
    # 根据中介关键词id获取竞争性关键词信息
    def get(self, midkeyid):
        compkeys = CompKey.query.filter(CompKey.midkeyid == midkeyid)  # 数据库查询所有匹配的数据
        return compkeys_schema.dump(compkeys)

    # 根据种子关键词id删除竞争性关键词信息
    def delete(self,midkeyid):
        delete_compkeys = CompKey.query.filter(CompKey.midkeyid == midkeyid)
        try:
            db.session.delete(delete_compkeys)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '竞争性关键词删除失败，该中介关键词不存在竞争性关键词'}
        return {"code": 200,
                'msg': '该中介关键词的竞争性关键词删除成功'}

api.add_resource(CompKeysMidKeyId, '/compkeys<int:midkeyid>')

# 竞争性关键词模块 /compkeys/<int:seedkeyid>
class CompKeysSeedKeyId(Resource):
    # 根据种子关键词id获取竞争性关键词信息
    def get(self, seedkeyid):
        compkeys = CompKey.query.filter(CompKey.seedkeyid == seedkeyid)  # 数据库查询所有匹配的数据
        return compkeys_schema.dump(compkeys)

    # 根据种子关键词id删除竞争性关键词信息
    def delete(self,seedkeyid):
        delete_compkeys = CompKey.query.filter(CompKey.seedkeyid == seedkeyid)
        try:
            db.session.delete(delete_compkeys)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '竞争性关键词删除失败，该种子关键词不存在竞争性关键词'}
        return {"code": 200,
                'msg': '该种子关键词的竞争性关键词删除成功'}
 
api.add_resource(CompKeysSeedKeyId, '/compkeys<int:seedkeyid>')

# 竞争性关键词模块 /compkeys/<int:compkeyid>
class CompKeysId(Resource):
    # 根据id获取竞争性关键词信息
    def get(self, compkeyid):
        compkeys = CompKey.query.filter(CompKey.id == compkeyid)  # 数据库查询所有匹配的数据
        return compkeys_schema.dump(compkeys)

    # 根据种子关键词id删除竞争性关键词信息
    def delete(self,compkeyid):
        delete_compkeys = CompKey.query.filter(CompKey.id == compkeyid)
        try:
            db.session.delete(delete_compkeys)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    'msg': '竞争性关键词删除失败'}
        return {"code": 200,
                'msg': '竞争性关键词删除成功'}

api.add_resource(CompKeysId, '/compkeys<int:compkeyid>')

# 竞争性关键词词频模块 /compkeys/<int:compkeyid>/frequency
class CompKeysFrequency(Resource):
    # 获取种子关键词所有月份的词频信息
    def get(self, compkeyid):
        compkeyfrequencys = CompKeyFrequency.query.filter(CompKeyFrequency.compkeyid == compkeyid)  # 数据库查询所有匹配的数据
        return compkeyfrequencys_schema.dump(compkeyfrequencys)

api.add_resource(CompKeysFrequency, '/compkeys/<int:compkeyid>/frequency')

# 竞争性关键词最后加权后的排名和竞争度 /compkeyfinal<int:seedkeyid>
class CompkeysFinal(Resource):
    def get(self, seedkeyid):
        compkeyfinals = CompkeyFinal.query.filter(CompkeyFinal.seedkeyid == seedkeyid)  # 数据库查询所有匹配的数据
        return compkeyfinals_schema.dump(compkeyfinals)

    def post(seld,seedkeyid):
        q_data = request.get_data() # 接收json数据
        q_dict = json.loads(q_data) # json数据解析

        add_seedkeyid = seedkeyid
        add_compkeyname = q_dict["compkeyname"]
        add_value = q_dict["value"]

        add_compkeyfinal = CompkeyFinal(
            seedkeyid = add_seedkeyid,
            compkeyname = add_compkeyname,
            value = add_value
        )
        try:
            db.session.add(add_compkeyfinal)
            db.session.commit()
        except:
            db.session.rollback()
            return {"code": 500,
                    "msg": "加权后竞争性关键词添加失败，数据存在空值或不合法"}
        return {"code": 200,
                "msg": "成功添加加权后竞争性关键词"}

api.add_resource(CompkeysFinal, '/compkeyfinal/<int:seedkeyid>')


# ------------------------------------竞争性关键词算法--------------------------------------------
class CompkeyAlgorithm(Resource):
    def get(self,seed_keyword,thousand):
        result = {}
        # 判断搜索的单词是否已存在
        flag = False
        for seed_keyword_searched_data in seedkeys_schema.dump(SeedKey.query.all()):
            if (seed_keyword == seed_keyword_searched_data['seedkeyname']) & (thousand == seed_keyword_searched_data['loglength']):
                print('种子关键词已存在......')
                result['seed_keyword'] = seed_keyword
                result['seed_keyword_id'] = seed_keyword_searched_data['id']
                flag = True
                # 将后端的数据整合到result中
                seedkey = SeedKey.query.filter_by(seedkeyname=seed_keyword).first()
                seed_keyword_id = seedkey.id
                if seedkey:
                    result['seed_keyword_volume'] = seedkey.volume
                    # 使用找到的 seedkey 的 id 来筛选 MidKey 表中的记录
                    midkeys = MidKey.query.filter_by(seedkeyid=seedkey.id).all()
                    midkeys_data = midkeys_schema.dump(midkeys)
                    for midkey_data in midkeys_data:
                        compkeys = Compkey.query.filter_by(midkeyid=midkey_data['id']).all()
                        # compkeys_data = compkeys_schema.dump(compkeys)
                        compkeys_data = {}
                        for compkey1 in compkeys:
                            compkeys_data[compkey1.compkeyname] = compkey1.compkeyvalue
                        midkey_data['compkeys'] = compkeys_data
                    result['mid_keywords'] = midkeys_data

                    # 往result中添加加权后的竞争性关键词
                    compkeyfinals = CompkeyFinal.query.filter_by(seedkeyid=seed_keyword_id).all()
                    compkeysfinal_data = []
                    for compkeyfinal in compkeyfinals:
                        compkeysfinal_data.append([compkeyfinal.compkeyname,compkeyfinal.value])
                    result['compkeys_final'] = compkeysfinal_data

                break
        if not flag:
            result = compkey.main_compkey(seed_keyword,thousand)
            # print(result)
            # 解析返回的数据
            seed_keyword = result['seed_keyword']
            seed_keyword_volume = result['seed_keyword_volume']
            compkeys_final = result['compkeys_final']
            mid_keywords = result['mid_keywords']
            seed_keyword_data = {
                "seedkeyname": seed_keyword,
                "volume": seed_keyword_volume,
                "logdate": "202301",
                "loglength": thousand
            }
            print('正在添加种子关键词......')
            response_add_seed_keyword = requests.request("POST", url_prefix + 'seedkeys', headers=headers, data=json.dumps(seed_keyword_data))
            seed_keyword_id = json.loads(response_add_seed_keyword.text)['id']
            result['seed_keyword_id'] = seed_keyword_id
            for mid_keyword in mid_keywords:
                print('正在添加中介关键词......')
                # print(mid_keyword)
                mid_keyword_data = {
                    "seedkeyid":seed_keyword_id,
                    "midkeyname":mid_keyword['midkeyname'],
                    "midkeyvalue":mid_keyword['midkeyvalue']
                }
                response_add_mid_keyword = requests.request("POST", url_prefix + 'midkeys', headers=headers, data=json.dumps(mid_keyword_data))
                print(response_add_mid_keyword.text)
                mid_keyword_id = json.loads(response_add_mid_keyword.text)['id']
                # 获取每个中介关键词的所有竞争性关键词
                comp_keywords = mid_keyword["compkeys"]
                for comp_keyword in comp_keywords:
                    comp_keyword_data = {
                        "seedkeyid":seed_keyword_id,
                        "midkeyid":mid_keyword_id,
                        "compkeyname":comp_keyword,
                        "compkeyvalue":comp_keywords[comp_keyword]
                    }
                    print('正在添加竞争关键词......')
                    response_add_comp_keyword = requests.request("POST", url_prefix + 'compkeys', headers=headers, data=json.dumps(comp_keyword_data))
                    print(response_add_comp_keyword.text)
            print('正在添加加权后的竞争关键词......')
            # 添加加权后所有竞争关键词的列表
            for compkey_final in compkeys_final:
                compkey_final_data = {
                    "seedkeyid": seed_keyword_id,
                    "compkeyname": compkey_final[0],
                    "value": compkey_final[1]
                }
                response_add_compkeyfinal = requests.request("POST", url_prefix + 'compkeyfinal/'+str(seed_keyword_id) , headers=headers, data=json.dumps(compkey_final_data))
              
        # 为该用户添加搜索记录（默认用户id为1）
        search_history = {
            "seedkeyid":seed_keyword_id
        }
        # 默认用户id=1
        resonse_add_history = requests.request("POST", url_prefix + 'history/1', headers=headers, data=json.dumps(search_history))
        print(resonse_add_history.text)
        return result
        
api.add_resource(CompkeyAlgorithm,'/compkey/<seed_keyword>/<int:thousand>')

# ------------------------------------获取所有搜索历史--------------------------------------------
class MySearchHistory(Resource):
    def get(self):
        my_search_histories = []
        search_histories = SearchHistory.query.all()
        for search_history in search_histories:
            seedkeyid = search_history.seedkeyid
            seedkey = SeedKey.query.filter(SeedKey.id == seedkeyid).first()
            compkeyfinals = compkeyfinals_schema.dump(CompkeyFinal.query.filter(CompkeyFinal.seedkeyid == seedkeyid).all()) 
            my_search_histories.append({
                "seedkeyname": seedkey.seedkeyname,
                "seedkeyvolume": seedkey.volume,
                "compkeys": compkeyfinals
            })
        return my_search_histories

api.add_resource(MySearchHistory,'/myhistory')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
    # 测试连接数据库是否成功
    # with app.app_context():
    #     with db.engine.connect() as conn:
    #         rs = conn.execute(text("select 1"))
    #         print(rs.fetchone())  # (1,)